using System.Collections.Generic;
using UIFramework.Core;
using UnityEngine;

namespace UIFramework
{
    /// <summary>
    /// UI的模板
    /// 提供预制体模板
    /// </summary>
    [CreateAssetMenu(fileName = "UISettings", menuName = "UI/UI Settings")]
    public class UISettings : ScriptableObject
    {
        [Tooltip("UI Frame的预制体")]
        [SerializeField] private UIFrame templateUIPrefab = null;
        [Tooltip("界面的预制体(包括面板和窗口)")]
        [SerializeField] private List<GameObject> screensToRegister = null;
        [Tooltip("实例化时是否停用")]
        [SerializeField] private bool deactivateScreenGOs = true;
 
        /// <summary>
        /// 实例化一个UI Frame对象
        /// </summary>
        public UIFrame CreateUIInstance(bool instanceAndRegisterScreens = true) 
        {
            var newUI = Instantiate(templateUIPrefab);

            if (instanceAndRegisterScreens) 
            {
                foreach (var screen in screensToRegister) 
                {
                    var screenInstance = Instantiate(screen);
                    var screenController = screenInstance.GetComponent<IScreenController>();

                    if (screenController != null) 
                    {
                        newUI.RegisterScreen(screen.name, screenController, screenInstance.transform);
                        // 停用隐藏
                        if (deactivateScreenGOs && screenInstance.activeSelf) 
                        {
                            screenInstance.SetActive(false);
                        }
                    }
                    else 
                    {
                        Debug.LogError("[UIConfig] 屏幕不包含此控制器，跳过实例化此控制器" + screen.name);
                    }
                }
            }

            return newUI;
        }
        
        
        private void OnValidate() 
        {
            // 查找为null被销毁的控制器
            List<GameObject> objectsToRemove = new List<GameObject>();
            for(int i = 0; i < screensToRegister.Count; i++) 
            {
                var screenCtl = screensToRegister[i].GetComponent<IScreenController>();
                if (screenCtl == null)
                {
                    objectsToRemove.Add(screensToRegister[i]);
                }
            }

            if (objectsToRemove.Count > 0) 
            {
                Debug.Log("[UISettings] 添加到屏幕预制列表中的某些游戏对象没有附加屏幕控制器！正在移除！");
                foreach (var obj in objectsToRemove) 
                {
                    Debug.Log("[UISettings] 移除 " + obj.name + "，因为没有屏幕控制器");
                    screensToRegister.Remove(obj);
                }
            }
        }
        
    }
}